package com.elong.android.specialhouse.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.IConfig;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.adapter.common.BaseViewHolder;
import com.elong.android.specialhouse.adapter.common.PowerAdapter;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.entity.AdImageInfo;
import com.elong.android.specialhouse.entity.ApartmentSearchParam;
import com.elong.android.specialhouse.entity.City;
import com.elong.android.specialhouse.entity.HomeAdsEntity;
import com.elong.android.specialhouse.entity.HouseInfoRequestParam;
import com.elong.android.specialhouse.entity.HouseItemList;
import com.elong.android.specialhouse.payment.PaymentHelper;
import com.elong.android.specialhouse.request.CollectionReq;
import com.elong.android.specialhouse.request.GetAdRequest;
import com.elong.android.specialhouse.request.GetSuggestHouseListReq;
import com.elong.android.specialhouse.ui.FlexibleListView;
import com.elong.android.specialhouse.ui.HomePageAdsView;
import com.elong.android.specialhouse.ui.HomePageAdsView.OnAdsItemClickListener;
import com.elong.android.specialhouse.ui.SuperListView;
import com.elong.android.specialhouse.utils.BDLocationManager;
import com.elong.android.specialhouse.utils.EventReportTools;
import com.elong.android.specialhouse.utils.FileUtils;
import com.elong.android.specialhouse.utils.ImageTypeUtil;
import com.elong.android.specialhouse.utils.StringUtils;
import com.elong.android.specialhouse.utils.ToastUtils;
import com.elong.android.specialhouse.utils.Utils;
import com.elong.framework.net.error.NetFrameworkError;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.nostra13.universalimageloader.cache.memory.impl.LRULimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("NewApi")
public class HomeActivity extends BaseVolleyActivity<IResponse<?>> implements BDLocationListener, OnItemClickListener,
        OnAdsItemClickListener, View.OnClickListener ,ViewTreeObserver.OnPreDrawListener,View.OnTouchListener{
    private static final String TAG = "HomeActivity";
    private static final String PAGE_NAME = "youfangHomePage";
    /**
     * 当特色公寓数目小于此数时显示特色城市
     */
    private static final int MIN_HOUSE_COUNT = 3 ;
    private static final int DEFAULT_PAGE_SIZE = 20 ;
    private static final String HOT_CITY_FILE_NAME = "hot_cities.txt";

    private HomePageAdsView AdsView;
    private FlexibleListView lvHome;
    private FlexibleListView lvHomeCity ;
    private PowerAdapter<HouseItemList> mHomeListAdapter;
//    private PowerAdapter<City> mHomeCityAdapter ;
    private List<HouseItemList> mHomeListEntities = new ArrayList<HouseItemList>();
    private List<HomeAdsEntity> mAdsEntities;
    private List<AdImageInfo> mAdsDataAdImageInfos;
    private TextView tvSearch;

    private View lvHeaderView;
    private ImageView ivMsg;
    private static final int START_PAGE_INDEX = 0 ;
    private int totalHouseCount = 0;
    private int currentPageIndex = START_PAGE_INDEX ;
    private GetSuggestHouseListReq getSuggestHouseListReq;
    DisplayImageOptions userPhotoOptions ;

    private int[] hotCityImgIds ;
    private boolean isHouseList = false ;
    List<City> hotCities = null ;

//    private ImageView netErrorTip ;
    private Button btnRetry ;
    private LinearLayout llHeaderBg ;
    private GestureDetector mGestureDetector ;

    // 定位信息
    private boolean isPosition = false ;
    private double latitude ;
    private double longitude ;

    LRULimitedMemoryCache bitmapMemoryCache;
    @Override
    protected void initContentView() {
        setContentView(R.layout.act_home);
        Account.init(this);

        IConfig.initServerUrl(this,R.raw.server);
        PaymentHelper.initPayment(getApplicationContext());

        getWindow().getDecorView().getViewTreeObserver()
                .addOnPreDrawListener(this);
        getSuggestHouseListReq = new GetSuggestHouseListReq();
        lvHome = (FlexibleListView) findViewById(R.id.lv_home);
        lvHomeCity = (FlexibleListView) findViewById(R.id.lv_home_city);
        lvHeaderView = View.inflate(this, R.layout.item_home_list_head, null);
        AdsView = (HomePageAdsView) lvHeaderView.findViewById(R.id.ads_view);
        tvSearch = (TextView) findViewById(R.id.tv_home_search);
        ivMsg = (ImageView) findViewById(R.id.common_message);
        ivMsg.setOnClickListener(this);
//        netErrorTip = (ImageView) findViewById(R.id.iv_net_error_tip);
        btnRetry = (Button) findViewById(R.id.btn_retry);
        btnRetry.setOnClickListener(this);

        llHeaderBg = (LinearLayout) findViewById(R.id.ll_home_header);
        ViewPropertyAnimator.animate(llHeaderBg).alpha(0).setDuration(100).start();
        mGestureDetector = new GestureDetector(HomeActivity.this, new MyGestureListener());
        lvHome.setOnTouchListener(this);
        lvHomeCity.setOnTouchListener(this);

//        initBDLocation();
        userPhotoOptions = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.default_user_photo).build() ;
        bitmapMemoryCache = new LRULimitedMemoryCache(2*1024*1024);

        // 组件初始化之后，请求数据
        getLocalion();
        requestAdsData();
        setupListView();
        setupHotCityList();
    }

    /**
     * 请求广告条数据
     */
    private void requestAdsData() {
        GetAdRequest req = new GetAdRequest();
        req.tagType = ImageTypeUtil.getImageSizeType(this);
        requestHttp(req, ApartmentAPI.getADInfoList, StringResponse.class);
    }

    /**
     * 网络请求获取suggest列表
     */
    private void requestSuggestHouseList(boolean isRefresh) {
        requestSuggestHouseList(isRefresh, isPosition);
    }

    /**
     *
     * @param isRefresh
     * @param isPosition
     */
    private void requestSuggestHouseList(boolean isRefresh,boolean isPosition) {
        if (isRefresh) {
            currentPageIndex = START_PAGE_INDEX;
        } else {
            currentPageIndex++ ;
        }
        getSuggestHouseListReq.IsPosition = isPosition;
        if (isPosition) {
            getSuggestHouseListReq.Latitude = latitude;
            getSuggestHouseListReq.Longitude = longitude;
            getSuggestHouseListReq.cityId = null ;
        } else {
            getSuggestHouseListReq.Latitude = 0;
            getSuggestHouseListReq.Longitude = 0;
            getSuggestHouseListReq.cityId = "20202"; // 默认北京
        }
        getSuggestHouseListReq.pageIndex = currentPageIndex;
        getSuggestHouseListReq.pageSize = DEFAULT_PAGE_SIZE;
        if (Account.getInstance().isLogin()) {
            getSuggestHouseListReq.userId = Account.getInstance().getUserId();
        }
        requestHttp(getSuggestHouseListReq, ApartmentAPI.getSuggestHouseList, StringResponse.class, isRefresh);
    }


    private void getHotCityImgIds() {
        TypedArray ar = this.getResources().obtainTypedArray(R.array.hot_city_imgs);
        int len = ar.length();
        hotCityImgIds = new int[len];
        for (int i = 0; i < len; i++) {
            hotCityImgIds[i] = ar.getResourceId(i, 0);
        }
        ar.recycle();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        setListener();
    }

    private void initBDLocation() {
        BDLocationManager.getInstance().requestLocation(this);
    }

    private void initData() {
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED);
    }

    private void setListener() {
        AdsView.setOnAdsItemClickListener(this);
        lvHome.setOnItemClickListener(this);
        lvHomeCity.setOnItemClickListener(this);
        tvSearch.setOnClickListener(this);
    }

    /**
     * 填充列表页
     */
    private void setupListView() {
//        netErrorTip.setVisibility(View.GONE);
        mHomeListAdapter = new PowerAdapter<HouseItemList>(HomeActivity.this, R.layout.item_home_list, mHomeListEntities) {
            @Override
            protected void convert(final BaseViewHolder holder, final HouseItemList item) {

                setupApartmentTextInfo(holder, item);
                holder.setImageUrl(R.id.iv_landlord_pic_url, item.LandlordPicUrl, R.drawable.default_user_photo);
                ImageLoader.getInstance().displayImage(item.LandlordPicUrl, ((ImageView) holder.getView(R.id.iv_landlord_pic_url)), userPhotoOptions);
                holder.setImageUrl(R.id.iv_apartment_image, item.RoomPicUrl);
                holder.setImageResource(R.id.iv_collection, item.IsCollected ? R.drawable.icon_collect_selected : R.drawable.icon_collect_unselected);
                holder.setVisible(R.id.iv_collection, false);
                holder.setOnClickListener(R.id.iv_collection, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CollectionReq req = new CollectionReq() ;
                        if (!Account.getInstance().isLogin()) {  //未登录，跳转到登录页面
                            goToLoginPage();
                            return;
                        }
                        req.UserId = Account.getInstance().getUserId() ;
                        req.HouseId = item.HouseId ;
                        req.Index = holder.getPosition() ;
                        if (item.IsCollected) {
                            requestHttp(req,ApartmentAPI.deleteCollectionInfo,StringResponse.class) ;
                        } else {
                            requestHttp(req,ApartmentAPI.addCollectionInfo,StringResponse.class) ;
                        }
//                        item.IsCollected = !item.IsCollected ;
//                        notifyDataSetChanged();
                    }
                });
            }
        };
        lvHome.addHeaderView(lvHeaderView);
        lvHome.setAdapter(mHomeListAdapter);
        lvHome.setOnRefreshListener(new SuperListView.OnPullDownRefreshListener() {
            @Override
            public void onRefresh() {
                requestSuggestHouseList(true);
            }
        });
        lvHome.setOnLoadMoreListener(new SuperListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (totalHouseCount <= mHomeListAdapter.getCount()) {
                    lvHome.onLoadMoreComplete();
                    ToastUtils.show(HomeActivity.this, "没有更多公寓了", Toast.LENGTH_SHORT);
                } else {
                    requestSuggestHouseList(false);
                }
            }
        });
    }

    /**
     * 设置特色城市列表
     */
    private void setupHotCityList() {
//        netErrorTip.setVisibility(View.GONE);
        getHotCityImgIds();
        String data = FileUtils.getCitiesData(this, HOT_CITY_FILE_NAME);
        try {
            JSONObject jo = JSONObject.parseObject(data);
            hotCities = JSONArray.parseArray(jo.getString(JSONConstants.ATTR_HOT_CITY_LIST), City.class);

        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        PowerAdapter<City> mHotCityAdapter = new PowerAdapter<City>(this, R.layout.item_home_hot_city,hotCities) {
            @Override
            protected void convert(BaseViewHolder holder, City item) {
                int resId = hotCityImgIds[holder.getPosition()];
                String key = String.valueOf(resId);
                Bitmap b = bitmapMemoryCache.get(key);
                if (null == b) {
                    // 在优化，放入线程中加载。
                    b = decodeResId(resId);
                    bitmapMemoryCache.put(key, b);
                }

                // holder.setImageResource(R.id.hot_city_photo,hotCityImgIds[holder.getPosition()]);
                holder.setImageBitmap(R.id.hot_city_photo, b);
            }
        };
        lvHomeCity.addHeaderView(lvHeaderView);
        lvHomeCity.setAdapter(mHotCityAdapter);
        lvHomeCity.setOnRefreshListener(new SuperListView.OnPullDownRefreshListener() {
            @Override
            public void onRefresh() {
                requestSuggestHouseList(true);
                requestAdsData();
            }
        });
        lvHomeCity.setOnLoadMoreListener(new SuperListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                lvHomeCity.onLoadMoreComplete();
            }
        });
    }

    // TODO 去登录页
    private void goToLoginPage() {
//        Intent intent = new Intent(this, LoginActivity.class);
//        intent.putExtra(AppConstants.BUNDLE_KEY_COME_FROM, TAG);
//        startActivity(intent);
    }


    /**
     * 设置公寓价格文字
     */
    private void setupApartmentTextInfo(BaseViewHolder holder, final HouseItemList item) {
        //设置公寓名
        holder.setText(R.id.tv_apartment_name, item.HouseName);
        //设置价格信息
        int price = StringUtils.format(item.DailyPrice);
        SpannableString priceSpan = new SpannableString("￥" + price + "/晚");
        int priceTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 22, this.getResources().getDisplayMetrics());
        priceSpan.setSpan(new AbsoluteSizeSpan(priceTextSize, false), 1, priceSpan.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        priceSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.theme_yellow)), 1, priceSpan.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        holder.setText(R.id.tv_daily_price, priceSpan);
        //设置公寓地址 有商圈显示商圈，无则显示行政区
        holder.setText(R.id.tv_address, !TextUtils.isEmpty(item.BusinessAreaName) ? item.BusinessAreaName : item.DistrictName);
        //设置出租类型
        switch (item.RentalType) {
            case 0:        // 整租 则显示户型
                holder.setText(R.id.tv_rental_type, item.RoomAndLobby);
                break;
            case 1:        // 单间
                holder.setText(R.id.tv_rental_type, "单间");
                break;
            case 2:        // 床位
                holder.setText(R.id.tv_rental_type, "床位");
                break;
            default:
                break;
        }
    }

    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
        // 处理网络返回结果
        String content = ((StringResponse) t).getContent();
        JSONObject result = JSONObject.parseObject(content);
        boolean isHandlerError = handleIsError(request, result);   //是否已经处理过IsError信息
        if (((ApartmentAPI) request.getRequestOption().getHusky()) == ApartmentAPI.getSuggestHouseList) {
            lvHome.onLoadMoreComplete();
            lvHome.onRefreshComplete();
            lvHomeCity.onRefreshComplete();
        }
        if (!isHandlerError) {
            switch ((ApartmentAPI) request.getRequestOption().getHusky()) {
                case getSuggestHouseList:
                    totalHouseCount = result.containsKey(JSONConstants.ATTR_HOUSE_COUNT) ? result.getIntValue(JSONConstants.ATTR_HOUSE_COUNT) : 0;
                    mHomeListEntities = JSONArray.parseArray(result.getString(JSONConstants.ATTR_HOUSE_ITEM_LIST), HouseItemList.class);
                    if (totalHouseCount < MIN_HOUSE_COUNT) {
                        lvHomeCity.setVisibility(View.VISIBLE);
                        lvHome.setVisibility(View.GONE);
                    } else {
                        lvHome.setVisibility(View.VISIBLE);
                        lvHomeCity.setVisibility(View.GONE);
                        if (mHomeListEntities != null && mHomeListEntities.size() > 0) {
                            if (currentPageIndex > START_PAGE_INDEX) {
                                mHomeListAdapter.addAll(mHomeListEntities);
                            } else {
                                mHomeListAdapter.replaceAll(mHomeListEntities);
                            }
                        }
                    }
                    break;
                case getADInfoList:
//                    if (mAdsDataAdImageInfos != null && mAdsDataAdImageInfos.size() > 0) {
//                        return;
//                    }
                    mAdsDataAdImageInfos = JSONArray.parseArray(result.getString(JSONConstants.ATTR_AD_IMAGE_INFO), AdImageInfo.class);
                    if (mAdsDataAdImageInfos != null && mAdsDataAdImageInfos.size() > 0) {
                        AdsView.invalidateAdsWithReadAds(mAdsDataAdImageInfos);
                    }
                    break;
                case addCollectionInfo:
                    if (result.containsKey(JSONConstants.ATTR_INDEX)) {
                        int index = result.getIntValue(JSONConstants.ATTR_INDEX);
                        mHomeListAdapter.getItem(index).IsCollected = true;
                        mHomeListAdapter.notifyDataSetChanged();
                        Toast.makeText(this, R.string.add_collection_success,Toast.LENGTH_SHORT).show();
                    }
                    break;
                case deleteCollectionInfo:
                    if (result.containsKey(JSONConstants.ATTR_INDEX)) {
                        int index = result.getIntValue(JSONConstants.ATTR_INDEX);
                        mHomeListAdapter.getItem(index).IsCollected = false;
                        mHomeListAdapter.notifyDataSetChanged();
                        Toast.makeText(this, R.string.cancel_collection_success,Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (((ApartmentAPI) request.getRequestOption().getHusky())) {
                case getSuggestHouseList:
                    if (currentPageIndex > START_PAGE_INDEX) {
                        currentPageIndex--;
                    } else {
                        lvHomeCity.setVisibility(View.VISIBLE);
                    }
                    break;
                case addCollectionInfo:
                    Toast.makeText(this, R.string.add_collection_failed,Toast.LENGTH_SHORT).show();
                    break;
                case deleteCollectionInfo:
                    Toast.makeText(this, R.string.cancel_collection_failed,Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break ;
            }
        }
    }

    @Override
    public void onTaskError(ElongRequest request, NetFrameworkError ex) {
        super.onTaskError(request, ex);
        switch (((ApartmentAPI) request.getRequestOption().getHusky())) {
            case getSuggestHouseList:
                lvHome.onLoadMoreComplete();
                lvHome.onRefreshComplete();
                lvHomeCity.onRefreshComplete();
                if (currentPageIndex > START_PAGE_INDEX) {
                    currentPageIndex--;
                } else {
//                    netErrorTip.setVisibility(View.VISIBLE);
                    lvHomeCity.setVisibility(View.VISIBLE);
                }
                break ;
        }
    }

    @Override
    public void onTaskCancel(ElongRequest request) {
        super.onTaskCancel(request);
        switch (((ApartmentAPI) request.getRequestOption().getHusky())) {
            case getSuggestHouseList:
                lvHome.onLoadMoreComplete();
                lvHome.onRefreshComplete();
                if (currentPageIndex > START_PAGE_INDEX) {
                    currentPageIndex-- ;
                }
                break ;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (view.getParent() == lvHome) {//特色公寓列表
            if (position > 1) {
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "suggestHouse");//推荐房源suggestHouse
                Intent intent = new Intent(this, ApartmentDetailsActivity.class);
                HouseInfoRequestParam param = new HouseInfoRequestParam();
                param.HouseItemList = mHomeListAdapter.getItem(position - 2);
                intent.putExtra("ApartmentInfoRequestParam", param);
                startActivity(intent);
            }
        } else {//特色城市列表
            if (position > 1) {
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "suggestCity");//推荐城市suggestCity
                goApartmentListActivity(hotCities.get(position - 2));
            }
        }
    }


    @Override
    public void onAdsItemClick(Context mContext, List<AdImageInfo> mAdvs, int position) {
        EventReportTools.sendPageSpotEvent(PAGE_NAME, "banner");//广告banner
        // 跳转H5
        if (!IConfig.CLICKABLE_MONKEY_ADS) {
            return;
        }
        Utils.handleAdvClick(HomeActivity.this, mAdvs.get(position), mAdvs.get(position).url);
    }
    /**
     * 跳转到公寓列表页
     */
    private void goApartmentListActivity(City item) {

        //todo
        ApartmentSearchParam param = new ApartmentSearchParam() ;
        param.CityID = item.getCityId() ;
        param.CityName = item.getCityName() ;
        Intent intent = new Intent(HomeActivity.this, ApartmentListActivity.class);
        intent.putExtra("ApartmentSearchParam", param);
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AdsView != null) {
            AdsView.onResume();
        }

    }
    @Override
    protected void onPause() {
        super.onPause();
        if (AdsView != null) {
            AdsView.onPause();
        }
    }

    private void getLocalion() {
        BDLocation location = BDLocationManager.getInstance().getCurrentLocation() ;
        if (BDLocationManager.getInstance().isLocateSuccess()) {
            if (location != null && StringUtils.isNotEmpty(location.getCity())) {
                ((TextView) findViewById(R.id.tv_home_search)).setText("当前位置是：" + location.getCity().toString());
                isPosition = true ;
                latitude = location.getLatitude() ;
                longitude = location.getLongitude() ;
                requestSuggestHouseList(true,true);
            }
        } else {
            isPosition = false ;
            requestSuggestHouseList(true,isPosition);
        }

    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        if (BDLocationManager.getInstance().isLocateSuccess()) {
            if (location != null && StringUtils.isNotEmpty(location.getCity())) {
                ((TextView) findViewById(R.id.tv_home_search)).setText("当前位置是：" + location.getCity().toString());
                isPosition = true ;
                latitude = location.getLatitude() ;
                longitude = location.getLongitude() ;
                requestSuggestHouseList(true,true);
            }
        } else {
//            BDLocationManager.getInstance().requestLocation(this);
            isPosition = false ;
            requestSuggestHouseList(true,isPosition);
        }
        BDLocationManager.getInstance().stopLocationService(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_home_search:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "searchCity");//搜索城市searchCity
                Intent intent = new Intent(HomeActivity.this, ApartmentCitySelectActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_retry :
                startActivity(new Intent(this, MyOrderActivity.class));
                break ;
            case R.id.common_message:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "message");//消息message
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return false;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected int getReceiverPriority() {
        return AppConstants.RECEIVER_PRIORITY_HOME ;
    }

    @Override
    protected boolean isHomeActivity() {
        return true ;
    }

    @Override
    public boolean onPreDraw() {
        return true;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mGestureDetector != null) {
            return mGestureDetector.onTouchEvent(event);
        }
        return super.onTouchEvent(event);
    }

    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (e1 != null && e2 != null && llHeaderBg != null) {
                if (e1.getY() - e2.getY() > 20 && Math.abs(velocityY) > 10) {
                    ViewPropertyAnimator.animate(llHeaderBg).alpha(1).setDuration(100).start();
                } else if (e2.getY() - e1.getY() > 20 && Math.abs(velocityY) > 10) {
                    ViewPropertyAnimator.animate(llHeaderBg).alpha(0).setDuration(100).start();
                }
            }
            return false;
        }
    }

    private Bitmap decodeResId(int resId){
        Bitmap b = BitmapFactory.decodeResource(getResources(),resId);
        return b;
    }
}